import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { URLS } from '../core/servers/server.url';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public loading = false;
  validateForm: FormGroup;
  public svgCode: any;
  constructor(
    private fb: FormBuilder,
    public http: HttpClient,
    private router: Router,
    private sanitizer: DomSanitizer
  ) {}

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      console.log(this.validateForm.value);
      this.loading = true;
      this.http
        .post('api' + URLS.user.login, {
          name: this.validateForm.value.name,
          pwd: this.validateForm.value.pwd
        })
        .subscribe((res: any) => {
          if (res.code === 0) {
            this.loading = false;
            localStorage.setItem('accessToken', res.data.name);
            this.router.navigate(['/default/home']);
          } else {
            this.loading = false;
          }
        });
    }
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      pwd: [null, [Validators.required]],
      code: [null, [Validators.required]]
    });
    this.rfCode();
  }
  // 获取验证码
  rfCode() {
    this.http
      .get('api' + URLS.user.getCaptcha + '?date=' + new Date().getTime())
      .subscribe((res: any) => {
        this.svgCode = this.sanitizer.bypassSecurityTrustHtml(res.data);
      });
  }
}
